package cn.turboinfo.fuyang.api.provider.common.service.impl.spec;

import cn.turboinfo.fuyang.api.domain.common.service.spec.SpecService;
import cn.turboinfo.fuyang.api.domain.common.service.spec.SpecSetRelService;
import cn.turboinfo.fuyang.api.domain.common.service.spec.SpecSetService;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.Spec;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.SpecSet;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.SpecSetRel;
import cn.turboinfo.fuyang.api.provider.common.repository.database.spec.SpecSetDAO;
import cn.turboinfo.fuyang.api.provider.common.repository.database.spec.SpecSetPO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.helper.service.impl.DefaultQServiceImpl;
import nxcloud.foundation.core.data.support.annotation.EnableSoftDelete;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@EnableSoftDelete
@Service
public class SpecSetServiceImpl extends DefaultQServiceImpl<SpecSet, Long, SpecSetPO, SpecSetDAO> implements SpecSetService {

    private final SpecSetRelService specSetRelService;

    private final SpecService specService;

    @Override
    public List<Spec> findWithHierarchy(Long specSetId) {
        Set<Long> specIdSet = specSetRelService.findBySpecSetId(specSetId).stream()
                .map(SpecSetRel::getId)
                .collect(Collectors.toSet());

        return findWithHierarchy(new HashSet<>(specIdSet));
    }

    @Override
    public List<Spec> findWithHierarchy(Collection<Long> specSetIdCollection) {
        return specService.findWithHierarchy(specSetIdCollection);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        // 删除关联表
        List<SpecSetRel> setRelList = specSetRelService.findBySpecSetId(id);
        for (SpecSetRel rel : setRelList) {
            specSetRelService.deleteById(rel.getId());
        }

        // 删除规格
        Set<Long> setIdSet = setRelList.stream()
                .map(SpecSetRel::getSpecSetId)
                .collect(Collectors.toSet());
        List<Spec> specList = specService.findWithHierarchy(setIdSet);
        specList.forEach(it -> specService.deleteById(it.getId()));

        super.deleteById(id);
    }
}
